package com.yitongmao.common;

import android.annotation.TargetApi;
import android.content.ContentResolver;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;

import com.yitongmao.util.Loger;
import com.yitongmao.util.StringUtils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class ImageUtils {
    /**
     * @param options
     * @param reqWidth
     * @param reqHeight
     * @return
     */
    public static int calculateInSampleSize(BitmapFactory.Options options,
                                            int reqWidth, int reqHeight) {
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {
            if (width > height) {
                inSampleSize = Math.round((float) height / (float) reqHeight);
            } else {
                inSampleSize = Math.round((float) width / (float) reqWidth);
            }
        }
        return inSampleSize;
    }

    public static void Bitmap2File(Bitmap bitmap, String filename) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(filename);
            fos.write(baos.toByteArray());
            fos.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null)
                    fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static Bitmap getUriBitmap(Context context, Uri uri, int reqWidth,
                                      int reqHeight) {
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        newOpts.inJustDecodeBounds = true;
        Bitmap bitmap = decodeUriAsBitmap(context, uri, newOpts);
        newOpts.inJustDecodeBounds = false;
        newOpts.inSampleSize = calculateInSampleSize(newOpts, reqWidth,
                reqHeight);
        bitmap = decodeUriAsBitmap(context, uri, newOpts);
        return bitmap;
    }

    public static Bitmap getStrBitmap(Context context, String picturePath, int reqWidth,
                                      int reqHeight) {
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        newOpts.inJustDecodeBounds = true;
        newOpts.inJustDecodeBounds = false;
        newOpts.inSampleSize = calculateInSampleSize(newOpts, reqWidth,
                reqHeight);
        /**
         * 获取图片的旋转角度，有些系统把拍照的图片旋转了，有的没有旋转
         */
        int degree = readPictureDegree(picturePath);
        Bitmap bitMapTemp = BitmapFactory.decodeFile(picturePath, newOpts);

        /**
         * 把图片旋转为正的方向
         */
        Bitmap bitmap = rotaingImageView(degree, bitMapTemp);
        return bitmap;
    }

    /**
     * 根据路径获得图片并压缩，返回bitmap用于显示
     *
     * @param filePath
     * @return
     */
    public static Bitmap getSmallBitmap(String filePath) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);

        options.inSampleSize = calculateInSampleSize(options, 320, 480);
        options.inJustDecodeBounds = false;
        Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);
        return bitmap;
    }

    public static Bitmap decodeUriAsBitmap(Context context, Uri uri,
                                           BitmapFactory.Options options) {

        Bitmap result = null;

        if (uri != null) {
            ContentResolver cr = context.getContentResolver();
            InputStream inputStream = null;
            try {
                inputStream = cr.openInputStream(uri);
                result = BitmapFactory.decodeStream(inputStream, null, options);
                inputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return result;
    }

    /**
     * 将Bitmap转换成InputStream
     *
     * @param bm
     * @return
     */
    public static InputStream bitmap2InputStream(Bitmap bm) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        InputStream is = new ByteArrayInputStream(baos.toByteArray());
        return is;
    }


    /**
     * 读取图片属性：旋转的角度
     *
     * @param path 图片绝对路径
     * @return degree旋转的角度
     */
    @TargetApi(Build.VERSION_CODES.ECLAIR)
    public static int readPictureDegree(String path) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }

    /*
        * 旋转图片
        * @param angle
        * @param bitmap
        * @return Bitmap
        */
    public static Bitmap rotaingImageView(int angle, Bitmap bitmap) {
        //旋转图片 动作
        Matrix matrix = new Matrix();
        matrix.postRotate(angle);
        System.out.println("angle2=" + angle);
        // 创建新的图片
        Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
                bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        return resizedBitmap;
    }


    public static String compressImage(String srcFilePath, int imgWidth) {
        String compressFilePath = "";
        if ("".equals(srcFilePath) || "null".equalsIgnoreCase(srcFilePath) || null == srcFilePath) {
            return "";
        }
        Bitmap bitmap;
        Bitmap bitmapTemp = BitmapFactory.decodeFile(srcFilePath);
        Loger.i("compressImage", "-compressImage-00-" + bitmapTemp.getWidth() + " , " + bitmapTemp.getHeight());
        if (bitmapTemp == null) {
            return "";
        } else {
            if (bitmapTemp.getWidth() > imgWidth) {
                float radio = (float) bitmapTemp.getWidth() / (float) bitmapTemp.getHeight();
                int with = bitmapTemp.getWidth();
                bitmap = getResizedBitmap(bitmapTemp, (with >= 720) ? 720 : with, 0, radio);
            } else {
                bitmap = bitmapTemp;
            }
        }
        Loger.i("compressImage", "-compressImage-02-" + bitmap.getWidth() + " , " + bitmap.getHeight());
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int options = 80;
        bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);
        boolean isBreak = false;
        while (baos.toByteArray().length / 1024 > 100 && !isBreak) {
            baos.reset();
            options -= 10;
            if (options <= 0) {
                isBreak = true;
                options = 10;
            }
            bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);
        }
        String fileName = System.currentTimeMillis() + ".jpg";
        String absoluteFolder = "";


        boolean sdCardExist = Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);
        String folderName = UrlConstants.CACHE_FOLDER + File.separator
                + UrlConstants.LOCAL_CLIENTTEMPLATE_DIR;
        if (sdCardExist) {
            absoluteFolder = Environment.getExternalStorageDirectory()
                    + File.separator + folderName + File.separator;
        } else {
            absoluteFolder = "";
        }

        Loger.i("AAA", "AAA--getui--absoluteFolder:" + absoluteFolder);
        if (!StringUtils.isBlank(absoluteFolder)) {
            File fileDir = new File(absoluteFolder);
            if (!fileDir.exists()) {
                fileDir.mkdirs();
            }
        }
        File file = new File(absoluteFolder, fileName);

        try {
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(baos.toByteArray());
            fos.flush();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (file != null && file.exists()) {
            compressFilePath = file.getAbsolutePath();
        }
        return compressFilePath;
    }

    public static String compressImages(String srcFilePath, int imgWidth) {
        String compressFilePath = "";
        if ("".equals(srcFilePath) || "null".equalsIgnoreCase(srcFilePath) || null == srcFilePath) {
            return "";
        }
        Bitmap bitmap;
        Bitmap bitmapTemp = BitmapFactory.decodeFile(srcFilePath);
        Loger.i("compressImage", "-compressImage-00-" + bitmapTemp.getWidth() + " , " + bitmapTemp.getHeight());
        if (bitmapTemp == null) {
            return "";
        } else {
            if (bitmapTemp.getWidth() > imgWidth) {
                float radio = (float) bitmapTemp.getWidth() / (float) bitmapTemp.getHeight();
                int with = bitmapTemp.getWidth();
                bitmap = getResizedBitmap(bitmapTemp, (with >= 720) ? 720 : with, 0, radio);
            } else {
                bitmap = bitmapTemp;
            }
        }
        Loger.i("compressImage", "-compressImage-02-" + bitmap.getWidth() + " , " + bitmap.getHeight());
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int options = 80;
        bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);
//        boolean isBreak = false;
//        while (baos.toByteArray().length / 1024 > 100 && !isBreak) {
//            baos.reset();
//            options -= 10;
//            if (options <= 0) {
//                isBreak = true;
//                options = 10;
//            }
//            bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);
//        }
        String fileName = System.currentTimeMillis() + ".jpg";
        String absoluteFolder = "";


        boolean sdCardExist = Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);
        String folderName = UrlConstants.CACHE_FOLDER + File.separator
                + UrlConstants.LOCAL_CLIENTTEMPLATE_DIR;
        if (sdCardExist) {
            absoluteFolder = Environment.getExternalStorageDirectory()
                    + File.separator + folderName + File.separator;
        } else {
            absoluteFolder = "";
        }

        Loger.i("AAA", "AAA--getui--absoluteFolder:" + absoluteFolder);
        if (!StringUtils.isBlank(absoluteFolder)) {
            File fileDir = new File(absoluteFolder);
            if (!fileDir.exists()) {
                fileDir.mkdirs();
            }
        }
        File file = new File(absoluteFolder, fileName);

        try {
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(baos.toByteArray());
            fos.flush();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (file != null && file.exists()) {
            compressFilePath = file.getAbsolutePath();
        }
        return compressFilePath;
    }

    //返回指定大小的bitmap；如果没有指定Height，就以传入的radio算出newHeight
    public static Bitmap getResizedBitmap(Bitmap bm, int newWidth, int newHeight, float radio) {
        float radioTemp = radio;
        float width = bm.getWidth();
        float height = bm.getHeight();
        if (radioTemp == 0.0f) {
            radioTemp = width / height;
            Loger.i("getResizedBitmap", "getResizedBitmap-radio:" + radioTemp);
            newHeight = (int) (((float) newWidth) / radioTemp);
        } else if (newHeight == 0) {
            newHeight = (int) (((float) newWidth) / radioTemp);
        }
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // CREATE A MATRIX FOR THE MANIPULATION
        Matrix matrix = new Matrix();
        // RESIZE THE BIT MAP
        matrix.postScale(scaleWidth, scaleHeight);

        // "RECREATE" THE NEW BITMAP
        Bitmap resizedBitmap = Bitmap.createBitmap(
                bm, 0, 0, (int) width, newHeight, matrix, false);
//        bm.recycle();
        return resizedBitmap;
    }

}
